//
//  SCLocationController.m
//  Scalper
//
//  Created by 王云 on 2017/9/21.
//  Copyright © 2017年 WY. All rights reserved.
//

#import "SCLocationController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

@interface SCLocationController ()<MAMapViewDelegate,AMapSearchDelegate>

@property (nonatomic, strong) MAMapView *mapView;
//大头针
@property (nonatomic, strong) MAPointAnnotation *annotation;
//定位
@property (nonatomic, strong) AMapLocationManager *locationManager;
//逆地理编码
@property (nonatomic, strong) AMapReGeocodeSearchRequest *regeo;
//逆地理编码使用的
@property (nonatomic, strong) AMapSearchAPI *search;

@property (nonatomic,weak)UILabel *titleL;
@property (nonatomic,weak)UILabel *detailL;
@property (nonatomic,weak)UIImageView *imgV;

@property (nonatomic,strong)NSDictionary *dic;

@end

@implementation SCLocationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    self.title = @"选择地址";
}
- (void)setUI{
    
    _mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    _mapView.showsScale = NO;
    [self.view addSubview:_mapView];
    
    
   
    UIView *addressView = [[UIView alloc] init];
    addressView.layer.cornerRadius = 4;
    addressView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:addressView];
    
    UIImageView *icon = [[UIImageView alloc] init];
    icon.image = [UIImage imageNamed:@"per_address"];
    [icon setContentMode:UIViewContentModeScaleAspectFit];
    [addressView addSubview:icon];
    
    UIButton *yesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [yesBtn setTitle:@"确定" forState:UIControlStateNormal];
    [yesBtn addTarget:self action:@selector(yesAction) forControlEvents:UIControlEventTouchUpInside];
    yesBtn.titleLabel.font = [UIFont systemFontOfSize:12];
        [yesBtn setTitleColor:TitleDarkColor forState:UIControlStateNormal];
    [addressView addSubview:yesBtn];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.numberOfLines = 2;
    titleL.font = [UIFont systemFontOfSize:14];
    [addressView addSubview:titleL];
    _titleL = titleL;
    
    UILabel *detailL = [[UILabel alloc] init];
    detailL.textColor = TitleDarkColor;
    detailL.font = [UIFont systemFontOfSize:12];
    [addressView addSubview:detailL];
    _detailL = detailL;
    
    UIImageView *imgV = [[UIImageView alloc] init];
//    imgV.hidden = YES;
    [imgV setTransform:CGAffineTransformMakeTranslation(0, -18)];
    imgV.image = [UIImage imageNamed:@"home_Red"];
    [self.view addSubview:imgV];
    _imgV = imgV;
    
    __weak __typeof(&*self)weakSelf = self;
    [addressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).offset(8);
        make.right.equalTo(weakSelf.view.mas_right).offset(-8);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-8);
        make.height.equalTo(@50);
    }];
    [icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(addressView);
        make.left.equalTo(addressView.mas_left).offset(8);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [yesBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(addressView);
        make.right.equalTo(addressView.mas_right).offset(-8);
        make.width.height.equalTo(@44);
    }];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(addressView.mas_top).offset(4);
        make.bottom.equalTo(addressView.mas_bottom).offset(-4);
        make.left.equalTo(icon.mas_right).offset(8);
        make.right.equalTo(yesBtn.mas_left).offset(-8);
    }];
    
    [detailL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleL.mas_bottom);
        make.left.equalTo(icon.mas_right).offset(8);
        make.right.equalTo(yesBtn.mas_left).offset(-8);
        make.height.equalTo(@21);
    }];
    [imgV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(weakSelf.view);
        make.size.mas_equalTo(imgV.image.size);
    }];
    
    //定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        DLog(@"%@",regeocode.formattedAddress);
        if (error) {
            return ;
        }
        weakSelf.titleL.text = regeocode.formattedAddress;
        //        weakSelf.detailL.text = [NSString stringWithFormat:@"%@%@%@",regeocode.district,regeocode.street,regeocode.number];
        //添加大头针
        weakSelf.annotation = [[MAPointAnnotation alloc]init];
        weakSelf.annotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
        [weakSelf.mapView addAnnotation:weakSelf.annotation];
        [_mapView setCenterCoordinate:CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) animated:YES];
        //让地图在缩放过程中移到当前位置试图
        [weakSelf.mapView setZoomLevel:15.1 animated:YES];
        
    }];
    
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc]init];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        // [_locationManager setDelegate:self];
        //设置不允许系统暂停定位
        [_locationManager setPausesLocationUpdatesAutomatically:NO];
        
        _locationManager.locationTimeout = 6;
        _locationManager.reGeocodeTimeout = 3;
    }
    return _locationManager;
}
- (AMapReGeocodeSearchRequest *)regeo {
    if (!_regeo) {
        _regeo = [[AMapReGeocodeSearchRequest alloc]init];
        _regeo.requireExtension = YES;
    }
    return _regeo;
}

- (AMapSearchAPI *)search {
    if (!_search) {
        _search = [[AMapSearchAPI alloc]init];
        _search.delegate = self;
    }
    return _search;
}


#pragma mark - map delegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
//    为了显示定位蓝点
   
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        if ([annotation isKindOfClass:[MAUserLocation class]]) {
            return nil;
        }
        static NSString *reuseIdetifier = @"annotationReuseIndetifier";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdetifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:reuseIdetifier];
        }
        //放一张大头针图片即可
        annotationView.image = [UIImage imageNamed:@"home_Red"];
        annotationView.centerOffset = CGPointMake(0, -18);
        return annotationView;
    }

    return nil;
}

- (void)mapView:(MAMapView *)mapView regionWillChangeAnimated:(BOOL)animated{

    [mapView removeAnnotations:self.mapView.annotations];
}

#pragma mark - 滑动地图结束修改当前位置
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)animated {
    
    _annotation.coordinate = mapView.centerCoordinate;
    //添加标注视图
    [mapView addAnnotation:_annotation];

    self.regeo.location = [AMapGeoPoint locationWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
    [self.search AMapReGoecodeSearch:self.regeo];
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response {
    

    
    if (response.regeocode != nil) {
        AMapReGeocode *reocode = response.regeocode;
        //地图标注的点的位置信息全在reoceode里面了
        DLog(@"%@",reocode.formattedAddress);
//        NSLog(@"%@",reocode.pois); //附近位置信息
        _titleL.text = reocode.formattedAddress;

        
        _dic = @{@"lat":[NSString stringWithFormat:@"%.3f",request.location.latitude],@"lon":[NSString stringWithFormat:@"%.3f",request.location.longitude],
                 @"city":_titleL.text};
    }
}

- (void)yesAction{
    if (_Maddress) {
        _Maddress(_dic);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
